define(['jquery','mylayer','asyncForm','wangEditor'], function ($,mylayer,asyncForm,wangEditor) {
	var app={
		init:function(op){
			var _this=this;
			//添加图片
	        $(".upload_post_img").off("click").on("click",function(){
	        	$('#upload_post')[0].click();
	        });
			//选择图片后上传预览
	        $("#upload_post").off("change").on("change",function(){
	        	var file=document.getElementById(this.id).files[0];
			    //Verify that the file type
			    if(file.type.indexOf("image")=="-1"){
			    	mylayer.showMessage("error",'请上传图片,检查格式');
			        return false;
			    }
				else{
					var index=$(".upload_post_list").size()+1;
					_this.upload(index);
				}
	        });
	        //输入url
	        $("#post_img_url").on("blur",function(){
	        	if($(this).hasClass('change')){
	        		var size=$(".upload_post_list").size();
		        	$("#image_error").hide();
	        	 	var url=$(this).val();
		        	if(url){
		        		var reg=new RegExp('[a-zA-z]+://[^\s]*');
			        	if(!reg.test(url)){
			        		mylayer.showMessage("error","请输入正确的图片地址");
			        		return false;
			        	}
						var urls=$(this).attr("urls")?$(this).attr("urls"):'';
						if(urls&&urls.indexOf(url)>-1){
							mylayer.showMessage("error","对不起，您已经上传");
							return false;
						}
						else{
							_this.upload(size+1,url);
						}
		        	}
	        	}
	        	$(this).removeClass('change');
	        });
	        //判断url是否改变
	        $("#post_img_url").on("change",function(){
	        	$(this).addClass('change');
	        });
	        //标题校验
	        $("#post_title").on("keyup",function(){
	        	var title=$.trim($(this).val());
	        	if(title==""){
	        		$(this).parent().find(".error_msg").html("请输入标题").show();
	        	}
	        	else{
	        		$(this).parent().find(".error_msg").html("").hide();
	        	}
	        });
	        //提交数据
	        $("#submit_post").off("click").on("click",function(){
	        	if($(this).hasClass('disabled')){
	        		return false;
	        	}
	        	var that=this;
	        	var flag=true;
	        	if($(".upload_post_list").size()==0){
	        		flag=false;
	        	}
	       		var title=$.trim($("#post_title").val());
	        	if(title==""){
	        		$("#post_title").parent().find(".error_msg").html("请输入标题").show();
	        		flag=false;
	        	}
	        	else{
	        		$("#post_title").parent().find(".error_msg").html("").hide();
	        	}
	        	var tags=$.trim($("#post_tags").val());
	        	if(!flag){
	        		return false;
	        	}
	        	else{
	        		$(this).addClass('disabled');
	        		var data={
	        			'img_info':_this.getImg_Str("img_name"),
	        			'title':$.trim($("#post_title").val()),
	        			'introduction':$.trim($("#post_introduction").val()),
	        			'description':$.trim($("#post_description").html()),
	        			'tags':$.trim($("#post_tags").val()),
	        			'assort':$.trim($("#post_assort").val()),
	        			'type':$.trim($("#post_type").val()),
	        			'url':$.trim($("#post_url").val())
	        		};
	        		var id=$(this).attr("data-id");
	        		if(id){
	        			data.id=id;
	        		}
	        		$.postAjax("/post/saveinfo",data,function(result){
	        			$(that).removeClass('disabled');
	        			if(result.code=="0x00000"){
	        				if(op&&typeof op.success=="function"){
        						op.success(result);
	        				}
	        				mylayer.showMessage("success","谢谢，发布成功");
	        				$(".layer_post_add").remove();
	        				$(".overlay_layer_post_add").remove();
	        			}
	        			else if(result.result){
	        				mylayer.showMessage("error",result.result);
	        			}
	        		},function(){
	        			$(that).removeClass('disabled');
	        			mylayer.showMessage("error","对不起,网络错误");
	        		});
	        	}
	        });
			//预览
			$("#post_preview").off("click").on("click",function(){
	        	var title=$.trim($("#post_title").val());
	        	var album=$.trim($("#post_album_value").val());
	        	if($(".upload_post_list").size()==0||title==""||album==""){
	        		mylayer.showMessage("error","请输入完整信息");
	        		return false;
	        	}
	        	else{
	        		_this.initPreview();
	        	}
			});
			//图片事件
	        if($(".upload_post_list").size()>0){
	        	this.upload_event();
	        }
	        //选择标签
	        $(".tag_list").off("click").on("click",function(){
	        	var tags=$.trim($("#post_tags").val());
	        	var tag=$.trim($(this).html());
	        	var tags_list=tags.split(" ");
        		var c_tags="";
        		var flag=true;
        		var value="";
        		for(var i=0;i<tags_list.length;i++){
        			value=$.trim(tags_list[i]);
        			if(value){
        				if(value==tag){
        					flag=false;
        					continue;
        				}
        				else{
        					c_tags+=value+" ";
        				}
        			}
        		}
	        	if($(this).hasClass('checked')){
	        		$(this).removeClass('checked');
	        		$("#post_tags").val(c_tags);
	        	}
	        	else{
	        		if(flag){
	        			$("#post_tags").val(tags+" "+tag);
	        		}
	        		$(this).addClass('checked');
	        	}
	        });
	        var editor = new wangEditor('post_description');
	         // 自定义菜单
		   // 使用英语
		    editor.config.lang = wangEditor.langs['en'];
		     // 字号
		    editor.config.fontsizes = {
		        // 格式：'value': 'title'
		        1: '10px',
		        3: '12px',
		        4: '13px',
		        5: '14px',
		        6: '15px',
		        7: '16px',
		        8: '17px',
		        9: '18px',
		        10: '20px',
		        11: '22px',
		        12: '24px',
		        13: '26px',
		        14: '28px'
		    };
		    // 自定义菜单
		    editor.config.menus = [
		   		'source',
		   		'img',
		        'bold',
		        'underline',
		        'italic',
		        'forecolor',
		        'bgcolor',
		        'fontfamily',
        		'fontsize',
        		'link',
        		'unlink',
        		'alignleft',
		        'aligncenter',
		        'alignright',
		        'insertcode',
		     ];
		    editor.create();
		    $(".wangeditor-menu-img-picture").off("click").on("click",function(){
		    	$("#editor_upload_post").click();
		    });
		    $("#editor_upload_post").off("change").on("change",function(){
		    	var file=document.getElementById(this.id).files[0];
			    //Verify that the file type
			    if(file.type.indexOf("image")=="-1"){
			    	mylayer.showMessage("error",'请上传图片,检查格式');
			        return false;
			    }
				else{
					_this.editorupload(editor);
				}
		    });
		},
		//图片上传
		upload:function(index,image_url){
			var _this=this;
			var op={
				beforeSend:function(){
					var html="<div class='upload_loading' id='upload_loading_"+index+"'><div class='bar'><span class='bar_progress'><span><span class='bar_value'></span></div></div>"
					$(".upload_post_lists").append(html);
					if(!_this.bar){
						_this.bar=window.setInterval(function(){
							$(".upload_loading .bar").each(function(){
								var x=Math.ceil(($(this).find(".bar_progress").width()/$(this).width())*100);
								if(x<99){
									$(this).find(".bar_progress").css("width",(x+1)+"%");
									$(this).find(".bar_value").html((x+1)+"%");
								}
							});
						},50);
					}
				},
				success:function(result){
					$("#upload_loading_"+index).remove();
					if(result.code=="0x00000"){
						if($(".upload_loading").size()==0){
							clearTimeout(_this.bar);
							_this.bar="";
						}
						var imgsrc=result.info.img_src?result.info.img_src:'';
						var img_md_str=result.info.img_md_str?result.info.img_md_str:'';
						var img_name=result.info.img_name?result.info.img_name:'';
						var size=$("upload_post_list").size();
						if(size<10){
							var html="<span md='"+img_md_str+"' image_url='"+(image_url?image_url:'')+"' data-src='"+imgsrc+"' img_name='"+img_name+"' class='upload_list upload_post_list'>"+
								"<img src='"+imgsrc+"' /><a class='remove_item' href='javascript:void(0)' title='remove'>×</a></span>";
							$(".upload_post_lists").append(html);
							_this.upload_event();
						}
						$(".photo_number").html($(".upload_post_list").size());
						$("#post_img_url").val("");
						if(image_url){
							var urls=$(this).attr("#post_img_url")?$(this).attr("#post_img_url"):'';
							$("#post_img_url").attr("urls",urls+image_url+";");
						}
						else{
							if($("#upload_post_form").size()>0){
								$("#upload_post_form")[0].reset();
							}
						}
					}
					else{
					 	if(result.result){
					 		mylayer.showMessage("error",result.result);
					 	}
					}
				},
				error:function(index){
					$("#upload_loading_"+index).remove();
					mylayer.showMessage("error","Sorry,please try it again!");
				},
				index:index
			};
			op.beforeSend();
			if(image_url){
				var data={'image_url':image_url};
				$.postAjax("/common/getimage",data,function(result){
					op.success(result);
				},function(){
					op.error(index);
				});
		  	}
		  	else{
		  		var form=document.getElementById("upload_post_form");
		  		var img_md_strs=this.getImg_Str('md');
		  		$("#img_md_strs").val(img_md_strs);
		  		$("#upload_file_name").val("upload_file");
		  		new asyncForm(form,op).submit(function(result,e){ 
                	op.success(result);
				});
		  	}
		},
		//图片上传
		editorupload:function(editor){
			var _this=this;
			var op={
				success:function(result){
					if(result.code=="0x00000"){
						var imgsrc=result.info.img_src?result.info.img_src:'';
						editor.command(null, 'insertHtml', '<img src="' + imgsrc + '" style="max-width:100%;"/>');
					}
					else{
					 	if(result.result){
					 		mylayer.showMessage("error",result.result);
					 	}
					}
				},
				error:function(){
					mylayer.showMessage("error","Sorry,please try it again!");
				}
			};
		  	var form=document.getElementById("editor_post_form");
	  		$("#upload_file_name").val("editor_upload_file");
	  		new asyncForm(form,op).submit(function(result,e){ 
            	op.success(result);
			});
		},
		//图片删除
		upload_event:function(){
			//删除图片
			$(".remove_item").off("click").on("click",function(){
	 	 		var img_info=$(this).parent().attr("img_name");
	 	 		var image_url=$(this).parent().attr("image_url");
	 	 		var upload_lists=$(this).parent().parent();
	            $(this).parent().remove();
	            var size=upload_lists.find(".upload_post_list").size();
	            $(".photo_number").html(size);
	            if(image_url){
					var url=$("#post_img_url").attr("urls");
					if(url.indexOf(image_url)>-1){
						var data=url.split(";");
						data.splice($.inArray(image_url,data),1); 
						$("#post_img_url").attr("urls",data.join(";"));
					}
				}
				$("#image_error").hide();
	            if($(this).hasClass('isVirtual')){
	            	return false;
				}
	 	 		$.postAjax("/share/tmppic_remove",{'img_info':img_info},function(result){});
			});
		},
		//获取图片相关信息
		getImg_Str:function(name){
			var result='';
			$(".upload_post_list").each(function(){
				result+=$(this).attr(name)+";";
			});
			if(result.length>0){
				result=result.substring(0,result.length-1);
			}
			return result;
		},
		initPreview:function(){
			
		}
	};
	return app;
});



